//
//  ShopsDetailViewController.m
//  EasyToTesco
//
//  Created by mc on 16/3/11.
//  Copyright © 2016年 Jack. All rights reserved.
//

#import "ShopsDetailViewController.h"
#import "HeaderFileForEasyToTesco.h"
#import "AFNetworking.h"
#import "UIImageView+WebCache.h"

#import "SDCycleScrollView.h"
#import "ShopsdetailOneTableViewCell.h"
#import "ShopsDetailTwoTableViewCell.h"
#import "ShopsDetailThreeTableViewCell.h"
#import "CWStarRateView.h"


@interface ShopsDetailViewController ()<UITableViewDataSource, UITableViewDelegate, SDCycleScrollViewDelegate>{
    //用于收回cell
    BOOL disbool;
    BOOL goodsbool;
}

@property (nonatomic , strong)NSMutableDictionary *shopIntDic;
//存放图片地址
@property (nonatomic, strong)NSMutableArray *shopsArr;

//存放商家评论的数组
@property (nonatomic, strong)NSMutableArray *shopDissArray;
//存放商家产品信息的数组
@property (nonatomic, strong)NSMutableArray *shopGoodsArray;

@property (nonatomic, strong)UITableView *shopsDetailtableview;

@end

@implementation ShopsDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self addshopsinitsth];
    
    [self addshopsDetopview];
    
    [self addShopsDetatableviewUI];
    
    [self addshopDetaildatasources];
    
    [self getshopgoodsdatasources];
    
    
}
- (void)addshopsinitsth {
    disbool = YES;
    goodsbool = YES;
    self.shopsArr = [@[]mutableCopy];
    self.shopDissArray = [@[]mutableCopy];
    self.shopGoodsArray = [@[]mutableCopy];
    self.shopIntDic = [[NSMutableDictionary alloc] initWithCapacity:0];
}

- (void)addshopsDetopview {
    
    UIImageView *image1 = [[UIImageView alloc] initWithFrame:CGRectMake(10, (self.secondView.frame.size.height-20)/2, 20, 20)];
    image1.image = [UIImage imageNamed:@"goback-icon.png"];
    [self.secondView addSubview:image1];
    self.leftBtn.hidden = YES;
    
    UIButton *goBackBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    goBackBtn.frame = CGRectMake(0, 0, self.secondView.frame.size.height, self.secondView.frame.size.height);
    [goBackBtn addTarget:self action:@selector(gobackClick) forControlEvents:UIControlEventTouchUpInside];
    [self.secondView addSubview:goBackBtn];
    self.titleLabel.text = @"商家详情";

}

- (void)gobackClick {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)addShopsDetatableviewUI {
    self.shopsDetailtableview = [[UITableView alloc] initWithFrame:CGRectMake(0, HIGHT*0.1, WEITH, HIGHT*0.9) style:UITableViewStyleGrouped];
    self.shopsDetailtableview.delegate = self;
    self.shopsDetailtableview.dataSource = self;
    self.shopsDetailtableview.tableFooterView = [[UIView alloc] init];
    [self.view addSubview:self.shopsDetailtableview];
}


#pragma mark -- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    } else if (section == 1) {
        return 3;
    } else if (section == 2){
        if (disbool == YES) {
            if (self.shopDissArray.count!=0) {
                return 1;
            } else {
            return 2;
            }
        } else {
            return self.shopDissArray.count;
        }
    }else {
        if (goodsbool == YES) {
            if (self.shopGoodsArray.count != 0) {
                return 1;
            }else{
                return 2;
            }
        } else {
            return self.shopGoodsArray.count;
        }
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        static NSString *identifier = @"ShopsdetailOneTableViewCell";
        ShopsdetailOneTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"ShopsdetailOneTableViewCell" owner:nil options:nil] lastObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        cell.shopstitlelabel.text = [NSString stringWithFormat:@"%@", self.shopIntDic[@"title"]];
        cell.shopCountylabel.text = [NSString stringWithFormat:@"所在地:%@", self.shopIntDic[@"s_county"]];
        cell.shopsScoreLabel.text = [NSString stringWithFormat:@"%@分", self.shopIntDic[@"score"]];
        cell.starview.scorePercent = [[NSString stringWithFormat:@"%@", self.shopIntDic[@"score"]] floatValue];
        return cell;
    } else if (indexPath.section == 1) {
        if (indexPath.row == 2) {
            
            static NSString *identifier = @"ShopsDetailThreeTableViewCell";
            ShopsDetailThreeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            if (cell == nil) {
                cell = [[[NSBundle mainBundle]loadNibNamed:@"ShopsDetailThreeTableViewCell" owner:nil options:nil] lastObject];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            
            
            cell.phoneNumLabel.text = [NSString stringWithFormat:@"%ld", [self.shopIntDic[@"dianhua"] integerValue]];
            return cell;
        } else {
            static NSString *identifier = @"ShopsDetailTwoTableViewCell";
        ShopsDetailTwoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"ShopsDetailTwoTableViewCell" owner:nil options:nil] lastObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
            if (indexPath.row == 0) {
                cell.titlelabel.text = [NSString stringWithFormat:@"经营范围:%@", self.shopIntDic[@"zycp"]];
                
            } else {
                cell.titlelabel.text = [NSString stringWithFormat:@"详细地址:%@", self.shopIntDic[@"dizhi"]];
            }
            return cell;
        }
    } else {
        //[iglun
        static NSString *identifier = @"shopsDetailcell2";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        return cell;
    }
    
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}
#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
<<<<<<< HEAD
    return 45;
=======
    if (indexPath.section == 0) {
        return 60;
    }
    
    return 50;
>>>>>>> dd1aac4040986135177ad18eb7781566439f59ee
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return HIGHT/3;
    } else {
<<<<<<< HEAD
        return 30;
=======
        return 20;
>>>>>>> dd1aac4040986135177ad18eb7781566439f59ee
    }
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] init];
    headerView.backgroundColor = [UIColor colorWithRed:52/255. green:147/255. blue:225/255. alpha:1];
    if (section == 0) {
        if (self.shopsArr.count!=0) {
            [self addSdcycleView:headerView];
        }
//        [self addSdcycleView:headerView];
    } else if (section == 1) {
<<<<<<< HEAD
        UILabel *titlebel = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, WEITH, 20)];
        titlebel.text = @"商家详情";
        [headerView addSubview:titlebel];
    } else if (section == 2) {
        UILabel *titlebel = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, WEITH, 20)];
        titlebel.text = @"商家评论";
=======
        headerView.backgroundColor = [UIColor whiteColor];
        UILabel *titlebel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, WEITH, 20)];
        titlebel.text = @"商家详情";
        titlebel.font = [UIFont systemFontOfSize:13];
        [headerView addSubview:titlebel];
    } else if (section == 2) {
        
        headerView.backgroundColor = [UIColor whiteColor];
        UILabel *titlebel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, WEITH, 20)];
        titlebel.text = @"商家评论";
        titlebel.font = [UIFont systemFontOfSize:13];
>>>>>>> dd1aac4040986135177ad18eb7781566439f59ee
        if (self.shopDissArray.count == 0) {
            titlebel.text = @"商家评论(该商家暂无评论)";
        }
        [headerView addSubview:titlebel];
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, WEITH, 30);
        [button addTarget:self action:@selector(headerBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = 230;
        [headerView addSubview:button];
    } else {
<<<<<<< HEAD
        UILabel *titlebel = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, WEITH, 20)];
        titlebel.text = @"商家产品";
=======
        
        headerView.backgroundColor = [UIColor whiteColor];
        UILabel *titlebel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, WEITH, 20)];
        titlebel.text = @"商家产品";
        titlebel.font = [UIFont systemFontOfSize:13];
>>>>>>> dd1aac4040986135177ad18eb7781566439f59ee
        if (self.shopGoodsArray.count == 0) {
            titlebel.text = @"商家产品(该商家暂无产品)";
        }
        [headerView addSubview:titlebel];
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, WEITH, 30);
        [button addTarget:self action:@selector(headerBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = 231;
        [headerView addSubview:button];
    }
    
    
    return headerView;
}


- (void)headerBtnClick:(UIButton *)button{
    if (button.tag == 230) {
        disbool = !disbool;
        
    }else {
        goodsbool = !goodsbool;
        
    }
    [self.shopsDetailtableview reloadData];
}

- (void)addSdcycleView:(UIView *)subview {
    //加载本地图片
//    NSArray *images = @[[UIImage imageNamed:@"L1.jpg"],
//                        [UIImage imageNamed:@"L2.jpg"],
//                        [UIImage imageNamed:@"L3.jpg"],
//                        [UIImage imageNamed:@"L4.jpg"]
//                        ];
    //加载网络图片
    // 情景二：采用网络图片实现
    NSArray *array = self.shopsArr;
    
    
    NSArray *imagesURL = [NSArray arrayWithArray:array];//@[

    // 情景三：图片配文字
//    NSArray *titles = @[@"感谢您的支持，如果下载的",
//                        @"如果代码在使用过程中出现问题",
//                        @"您可以发邮件到gsdios@126.com",
//                        @"感谢您的支持"
//                        ];

    CGFloat w = [UIScreen mainScreen].bounds.size.width;
    // 创建不带标题的图片轮播器
    SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, w, HIGHT/3) imageURLsGroup:imagesURL];
    cycleScrollView.delegate = self;
    [subview addSubview:cycleScrollView];
    // 轮播时间间隔，默认1.0秒，可自定义
    cycleScrollView.autoScrollTimeInterval = 4.0;
  
    
}
//轮播图的代理方法
#pragma mark - SDCycleScrollViewDelegate
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
    NSLog(@"---点击了第%ld张图片", index);
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.5;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footview = [[UIView alloc] init];
    return footview;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1&&indexPath.row == 2) {
        
        UIWebView*callWebview =[[UIWebView alloc] init];
        NSString *telStr =[NSString stringWithFormat:@"%@", self.shopIntDic[@"dianhua"]];
        NSLog(@"%@, %ld", telStr,[telStr integerValue]);
        NSURL *telURL =[NSURL URLWithString:[NSString stringWithFormat:@"tel://%ld", [telStr integerValue]]];// 貌似tel:// 或者 tel: 都行
        [callWebview loadRequest:[NSURLRequest requestWithURL:telURL]];
        //记得添加到view上
        [self.view addSubview:callWebview];
        
        
    }
}




//商家详情

- (void)addshopDetaildatasources {
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSString *shopid = self.shopsID;
    NSString *username = @"13282008515";
    
    NSDictionary *param = @{@"id":[NSString stringWithFormat:@"%@", shopid], @"username":[NSString stringWithFormat:@"%@", username]};
    
    [mgr POST:@"http://www.ylgw8.com/AppShop/Getshop" parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
<<<<<<< HEAD
=======
        
        
>>>>>>> dd1aac4040986135177ad18eb7781566439f59ee
        NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        
        self.shopIntDic = [self toArrayOrNSDictionary:responseObject];
        
        NSMutableArray *arr = [@[]mutableCopy];
//        arr = [NSMutableArray arrayWithArray:self.shopIntDic[@"jypic"]];
<<<<<<< HEAD
=======
        
//        NSLog(@"%@",arr);
>>>>>>> dd1aac4040986135177ad18eb7781566439f59ee
        if ([self.shopIntDic[@"sdpic"] length]!=0) {
            [arr addObject:[NSString stringWithFormat:@"%@", self.shopIntDic[@"sdpic"]]];
        }
        
        
        for (NSString *ff in self.shopIntDic[@"jypic"]) {
            if (ff.length!=0) {
                [arr addObject:ff];
            }
        }
        
        
         NSString *imageStr = [[[NSString stringWithFormat:@"%@", [self.shopIntDic[@"picprex"] objectForKey:@"m"]] componentsSeparatedByString:@" "] firstObject];
        
        self.shopsArr = [@[]mutableCopy];
        for (NSString *str in arr) {
            [self.shopsArr addObject:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", imageStr, str]]];
        }
        
        
        
        NSLog(@"%@----%@", self.shopIntDic, string);
        
        [self.shopsDetailtableview reloadData];
    } failure:^(AFHTTPRequestOperation *operation,NSError *error)
     {
         //         operation.response.statusCode;//404 401之类
                  NSLog(@"数据请求错误原因:%@", error);
                  NSLog(@"数据请求错误码:%ld", (long)operation.response.statusCode);
     }];
}

// 将JSON串转化为字典或者数组
- (id)toArrayOrNSDictionary:(NSData *)jsonData{
    NSError *error = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
                                                    options:NSJSONReadingAllowFragments
                                                      error:&error];
    
    if (jsonObject != nil && error == nil){
        return jsonObject;
    }else{
        // 解析错误
        return nil;
    }
}

//商家产品
- (void)getshopgoodsdatasources {
    
  AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSString *shopid = self.shopsID;

    NSDictionary *param = @{@"id":[NSString stringWithFormat:@"%@", shopid]};
    
    [mgr POST:@"http://www.ylgw8.com/AppShop/Getcp" parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        
         NSLog(@"%@", string);
        
        //商家产品数组
//        self.shopGoodsArray
        
        
        [self.shopsDetailtableview reloadData];
    } failure:^(AFHTTPRequestOperation *operation,NSError *error)
     {
         //         operation.response.statusCode;//404 401之类
//         NSLog(@"数据请求错误原因:%@", error);
//         NSLog(@"数据请求错误码:%ld", (long)operation.response.statusCode);
     }];
}

//获取商的评论
- (void)getShopdiscussdatasources {
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSString *shopid = self.shopsID;
        NSString *P = @"1";
    
    NSDictionary *param = @{@"id":[NSString stringWithFormat:@"%@", shopid], @"P":[NSString stringWithFormat:@"%@", P]};
    
    [mgr POST:@"http://www.ylgw8.com/AppShop/Getsjpj" parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        
        NSLog(@"%@", string);
        
        //商家评论数组
//        self.shopDissArray
        
        [self.shopsDetailtableview reloadData];
    } failure:^(AFHTTPRequestOperation *operation,NSError *error)
     {
         //         operation.response.statusCode;//404 401之类
         //         NSLog(@"数据请求错误原因:%@", error);
         //         NSLog(@"数据请求错误码:%ld", (long)operation.response.statusCode);
     }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
